package com.sx.manage.service.consumer.referee;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sx.manage.biz.consumer.info.IMNetworkPersonConsumerBiz;
import com.sx.manage.service.company.IMBaseCompanyService;
import com.sx.manage.service.consumer.IMBaseConsumerOperationInfoService;
import com.sx.manage.service.consumer.info.IMConsumerOperationInfoService;
import com.sx.manage.service.sys.IMBaseSystemConfigInfoService;
import com.sx.manage.util.WebServiceUtils;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.constants.type.consumer.operation.ReceiveStatus;
import com.sx.model.manage.mybatis.form.consumer.MConsumerOperationInfoForm;
import com.sx.model.manage.mybatis.form.consumer.MPersonalConsumerNetworkForm;
import com.sx.model.manage.mybatis.form.consumer.feedback.MRefereeViewForm;
import com.sx.model.manage.mybatis.form.sys.MSystemConfigInfoForm;
import com.sx.model.manage.mybatis.vo.company.MCompanyVO;
import com.sx.model.manage.mybatis.vo.consumer.MConsumerOperationInfoVO;
import com.sx.model.manage.mybatis.vo.consumer.MPersonalConsumerNetworkVO;
import com.sx.model.manage.mybatis.vo.consumer.feedback.MRefereeViewVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.sys.MSysConfigVO;
import com.sx.model.manage.mybatis.vo.util.MsgVO;

@Service("refereeWebServiceImpl")
public class RefereeWebServiceImpl {
	/** 转账 使用，固定为1 **/
	public static final String APPLICATION_CODE = "1";
	/*** 日志 */
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "consumerOperationInfoServiceImpl")
	private IMConsumerOperationInfoService consumerOperationInfoServiceImpl;

	@Resource(name = "mBaseConsumerOperationInfoServiceImpl")
	private IMBaseConsumerOperationInfoService mBaseConsumerOperationInfoServiceImpl;

	@Resource(name = "mNetworkPersonConsumerBizImpl")
	private IMNetworkPersonConsumerBiz mNetworkPersonConsumerBizImpl;

	// @Resource(name = "platformService")
	// private IPlatformServiceInterface platformServiceImpl;

	// @Resource(name = "orderServiceInterface")
	// private IOrderServiceInterface orderServiceInterface;

	@Resource(name = "mBaseCompanyServiceImpl")
	private IMBaseCompanyService mBaseCompanyServiceImpl;

	@Resource(name = "webServiceUtils")
	private WebServiceUtils webServiceUtils;

	@Resource(name = "mBaseSystemConfigInfoServiceImpl")
	private IMBaseSystemConfigInfoService mBaseSystemConfigInfoServiceImpl;

	/** 获取用户分页信息 */
	public ResultListVO<MRefereeViewVO> queryRefereeConsumer(MRefereeViewForm form) {
		log.debug(" 推荐发钱界面跳转数据查询form={}", form);
		return mNetworkPersonConsumerBizImpl.queryRefereeConsumer(form);
	}

	/** 查询能够领取奖励的 注册用户 */
	public ResultListVO<MPersonalConsumerNetworkVO> queryNetworkConsumer(MPersonalConsumerNetworkForm form) {
		log.debug("注册发钱界面跳转数据查询form={}", form);
		if (null != form.getCreate_date() && null != form.getCreate_date_end()) {
			if (form.getCreate_date().after(form.getCreate_date_end())) {
				return new ResultListVO<MPersonalConsumerNetworkVO>(false, null, "开始日期不能晚于结束日期");
			}
		}
		return mNetworkPersonConsumerBizImpl.queryNetworkConsumer(form);
	}

	/** 推荐人领取奖励 */
	public ResultBooleanVO receiveBatch(Long[] bind_consumer_ids) {
		if (null == bind_consumer_ids || 0 == bind_consumer_ids.length) {
			log.info("参数为空bind_consumer_ids is null");
			return new ResultBooleanVO("m.parameter.is.null");
		}
		ResultBooleanVO result = null;
		MsgVO msgVO = new MsgVO();
		for (Long bind_consumer_id : bind_consumer_ids) {
			result = receive(bind_consumer_id);
			if (!result.isSuccess()) {
				MPersonalConsumerNetworkVO networkVO = mNetworkPersonConsumerBizImpl.get_consumer_byId(bind_consumer_id).getObjVo();
				msgVO.append(networkVO.getConsumer_name() + ":" + result.getMsg());
			}
		}
		if (msgVO.getError().length() > 0) {
			log.error("推荐人领取奖励失败error={}", msgVO.getError());
			result = new ResultBooleanVO(false, null, msgVO.getError());
		}
		return result;
	}

	/** 推荐人领取奖励 */
	public ResultBooleanVO receive(Long bind_consumer_id) {
		log.info("推荐人领取奖励 consumer_id={}", bind_consumer_id);
		// 查询推荐人的推荐码
		MConsumerOperationInfoVO bindOperationVO = mBaseConsumerOperationInfoServiceImpl.queryByConsumerId(bind_consumer_id).getObjVo();
		if (StringUtils.isBlank(bindOperationVO.getReferral_code_referee())) {
			log.info("没有推荐人，程序终止consumer_id={}", bind_consumer_id);
			return new ResultBooleanVO(false, null, "没有填写推荐人，不能领取奖励");
		}
		if (!ReceiveStatus.CAN_RECEIVE.equals(bindOperationVO.getReceive_status())) {
			log.info("不是可领取状态consumer_id={},receive_status={}", bind_consumer_id, bindOperationVO.getReceive_status());
			return new ResultBooleanVO(false, null, "不是可领取状态");
		}
		// 根据推荐码查询推荐人
		// 根据推荐码查询个人
		MConsumerOperationInfoForm operQueryForm = new MConsumerOperationInfoForm();
		operQueryForm.setReferral_code_self(bindOperationVO.getReferral_code_referee());
		List<MConsumerOperationInfoVO> operList = mBaseConsumerOperationInfoServiceImpl.queryListByForm(operQueryForm).getData();
		if (null == operList || 1 != operList.size()) {
			log.info("推荐码不能确定唯一性程序终止referral_code_referee={}", bindOperationVO.getReferral_code_referee());
			return new ResultBooleanVO(false, null, "填写的推荐码，不能确定推荐人，操作失败。");
		}
		// 修改被推荐人推荐码的状态
		ResultBooleanVO result = consumerOperationInfoServiceImpl.updateReceiveStatus(bind_consumer_id, ReceiveStatus.RECEIVE);
		if (!result.isSuccess()) {
			log.info("修改被推荐人推荐码状态失败error={}", result.getMsg());
			return result;
		}
		Long consumer_id = operList.get(0).getConsumer_id();
		// 领取奖励 未完成 应该还需要查询，推荐人、被推荐人的 子账号、交易会员代码、摊位号的信息，等待接口中。。。
		BigDecimal amount = this.recommendedAmount();
		if (null == amount) {
			log.info("系统没有配置推荐人领取的奖励金额amount={}", amount);
			return new ResultBooleanVO("sx.system.recommended.amount");
		}
		// 个人子账户
		String personAccountNo = webServiceUtils.queryAccountNo(consumer_id);
		// 获取公司的 子账号、交易会员代码,订单号
		MCompanyVO companyVO = mBaseCompanyServiceImpl.query_company_S_X();
		String companyAccountNo = webServiceUtils.queryAccountNoCompany(companyVO.getId());
		String companyTradeMemCode = webServiceUtils.queryTradeMemberCodeCompany(companyVO.getId());
		String orderNo = null;// orderServiceInterface.makeOrderNo();
		// 创建总订单
		boolean ret = false;//orderServiceInterface.orderCreateOrUpdate(orderNo, amount, companyAccountNo, "推荐奖励", personAccountNo, "推荐奖励", COrderType.TRANSFER, COrderStatus.PREPARED);
		if (!ret) {
			log.info("创建总订单失败，注册奖励领取失败consumer_id={}", bind_consumer_id);
			consumerOperationInfoServiceImpl.updateReceiveStatus(bind_consumer_id, ReceiveStatus.CAN_RECEIVE);
			return new ResultBooleanVO(false, null, "创建总订单失败，注册奖励领取失败");
		}
//		// 生成转账信息
//		CTransferOrderEntity transferEntity = new CTransferOrderEntity();
//		transferEntity.setApplication_code(APPLICATION_CODE);
//		transferEntity.setCreate_time(new Date());
//		transferEntity.setRemark("推荐奖励");
//		transferEntity.setOrder_type(COrderType.TRANSFER);
//		transferEntity.setFrom_account_no(companyAccountNo);
//		transferEntity.setTo_account_no(personAccountNo);
//		transferEntity.setTrade_mem_code(companyTradeMemCode);
//		transferEntity.setOrder_no(orderNo);
//		transferEntity.setAmount(amount);
//		log.info("推荐人领取奖励transferEntity={}", transferEntity);
//		log.info("推荐人奖励companyAccountNo={},personAccountNo={},orderNo={}", companyAccountNo, personAccountNo, orderNo);
//		CTransferOrderEntity transfer = platformServiceImpl.consume(transferEntity);
//		if (null == transfer || !COrderStatus.INPROGRESS.equals(transfer.getOrder_status())) {
//			// 转账失败，将推荐码状态修改为原来的 ‘可领取’状态
//			log.info("推荐领取奖励失败 companyAccountNo={},personAccountNo={},orderNo={},order_status={}", companyAccountNo, personAccountNo, transfer.getOrder_no(), transfer.getOrder_status());
//			return consumerOperationInfoServiceImpl.updateReceiveStatus(bind_consumer_id, ReceiveStatus.CAN_RECEIVE);
//		}
//		log.info("推荐领取奖励完成 companyAccountNo={},personAccountNo={},orderNo={},order_status={}", companyAccountNo, personAccountNo, transfer.getOrder_no(), transfer.getOrder_status());
		return new ResultBooleanVO();
	}

	/** 注册领取奖励 */
	public ResultBooleanVO registerReceive(Long consumer_id) {
		log.info("注册领取奖励 consumer_id={}", consumer_id);
		ResultBooleanVO result = mNetworkPersonConsumerBizImpl.receiveRegisterReward(consumer_id);
		if (!result.isSuccess()) {
			log.error("领取奖励失败");
			return result;
		}
		// 领取奖励 未完成 应该还需要查询，推荐人、被推荐人的 子账号、交易会员代码、摊位号的信息，等待接口中。。。
		BigDecimal amount = this.registerdAmount();
		if (null == amount) {
			log.info("系统没有配置注册领取的奖励金额amount={}", amount);
			return new ResultBooleanVO("sx.system.recommended.amount");
		}
		// 个人子账户
		String personAccountNo = webServiceUtils.queryAccountNo(consumer_id);
		if (StringUtils.isBlank(personAccountNo)) {
			log.info("用户子账户不存在consumer_id={},personAccountNo={}", consumer_id, personAccountNo);
			return new ResultBooleanVO("m.consumer.relation.bank.account.code.is.not.exists");
		}

		// 获取公司的 子账号、交易会员代码,订单号
		MCompanyVO companyVO = mBaseCompanyServiceImpl.query_company_S_X();
		String companyAccountNo = webServiceUtils.queryAccountNoCompany(companyVO.getId());
		if (StringUtils.isBlank(companyAccountNo)) {
			log.info("用户子账户不存在company_id={},companyAccountNo={}", companyVO.getId(), companyAccountNo);
			return new ResultBooleanVO("m.company.relation.bank.account.code.is.not.exists");
		}
		String companyTradeMemCode = webServiceUtils.queryTradeMemberCodeCompany(companyVO.getId());
//		String orderNo = orderServiceInterface.makeOrderNo();
//		// 创建总订单
//		boolean ret = orderServiceInterface.orderCreateOrUpdate(orderNo, amount, companyAccountNo, "注册奖励", personAccountNo, "注册奖励", COrderType.TRANSFER, COrderStatus.PREPARED);
//		if (!ret) {
//			log.info("创建总订单失败，注册奖励领取失败consumer_id={}", consumer_id);
//			mNetworkPersonConsumerBizImpl.receiveRegisterRewardFail(consumer_id);
//			return new ResultBooleanVO(false, null, "创建总订单失败，注册奖励领取失败");
//		}
//		// 生成转账信息
//		CTransferOrderEntity transferEntity = new CTransferOrderEntity();
//		transferEntity.setApplication_code(APPLICATION_CODE);
//		transferEntity.setCreate_time(new Date());
//		transferEntity.setRemark("注册奖励");
//		transferEntity.setOrder_type(COrderType.TRANSFER);
//		transferEntity.setFrom_account_no(companyAccountNo);
//		transferEntity.setTo_account_no(personAccountNo);
//		transferEntity.setTrade_mem_code(companyTradeMemCode);
//		transferEntity.setOrder_no(orderNo);
//		transferEntity.setAmount(amount);
//		log.info("注册领取奖励transferEntity={}", transferEntity);
//		log.info("注册领取奖励companyAccountNo={},personAccountNo={},orderNo={}", companyAccountNo, personAccountNo, orderNo);
//		CTransferOrderEntity transfer = platformServiceImpl.consume(transferEntity);
//		if (null == transfer || !COrderStatus.INPROGRESS.equals(transfer.getOrder_status())) {
//			log.info("注册领取奖励失败 companyAccountNo={},personAccountNo={},orderNo={},order_status={}", companyAccountNo, personAccountNo, transfer.getOrder_no(), transfer.getOrder_status());
//			// 转账失败，将推荐码状态修改为原来的 ‘可领取’状态
//			return mNetworkPersonConsumerBizImpl.receiveRegisterRewardFail(consumer_id);
//		}
//		log.info("注册领取奖励完成 companyAccountNo={},personAccountNo={},orderNo={},order_status={}", companyAccountNo, personAccountNo, transfer.getOrder_no(), transfer.getOrder_status());
		return new ResultBooleanVO();
	}

	/** 推荐人获取的金额 **/
	public BigDecimal recommendedAmount() {
		MSystemConfigInfoForm form = new MSystemConfigInfoForm();
		form.setConfig_name(MSystemConstants.RECOMMENTED_AMOUNT);
		log.info("获取公式配置的推荐人能够领取的奖励form={}", form);
		try {
			MSysConfigVO configVO = mBaseSystemConfigInfoServiceImpl.queryByIdSystemConfig(form).getObjVo();
			if (null != configVO) {
				return new BigDecimal(configVO.getConfig_value());
			}
		} catch (Exception e) {
			log.error("获取公式配置的推荐人能够领取的奖励异常error={}", e);
		}
		return null;
	}

	/** 注册获取的金额 **/
	public BigDecimal registerdAmount() {
		MSystemConfigInfoForm form = new MSystemConfigInfoForm();
		form.setConfig_name(MSystemConstants.REGISTER_AMOUNT);
		log.info("获取公式配置的注册用户能够领取的奖励form={}", form);
		try {
			MSysConfigVO configVO = mBaseSystemConfigInfoServiceImpl.queryByIdSystemConfig(form).getObjVo();
			if (null != configVO) {
				return new BigDecimal(configVO.getConfig_value());
			}
		} catch (Exception e) {
			log.error("获取公式配置的注册用户能够领取的奖励异常error={}", e);
		}
		return null;
	}

}
